package com.wang.sort;

import java.util.Arrays;

/**
 * 二分查找法
 */
public class BinarySearchTest {
    static final int[] arrays = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    public static void main(String[] args) {
        System.out.println(search(arrays, 0,0,arrays.length-1));
    }

    public static int search(int[] arrays,int value,int low,int high){
        if(value < arrays[low] || value > arrays[high]){
            return -1;
        }
        int mid = (low + high) / 2;
        if(value > arrays[mid]){
            System.out.println("查询"+mid+"在右边");
            low = mid + 1;
            return search(arrays,value,low,high);
        }else if(value < arrays[mid]){
            System.out.println("查询"+mid+"在左边");
            high = mid - 1;
            return search(arrays,value,low,high);
        }else{
            System.out.println("命中"+mid);
            return mid;
        }
    }

    public static int search(int[] arrays, int value) {
        while (arrays.length >=1) {
            int mid = arrays.length / 2;
            if (value > arrays[mid]) {
                System.out.println("右边");
                // 右边
                arrays = Arrays.copyOfRange(arrays, mid+1, arrays.length);
            } else if (value < arrays[mid]) {
                System.out.println("左边");
                // 左边
                arrays = Arrays.copyOfRange(arrays, 0, mid - 1);
            } else {
                return mid;
            }
        }
        return -1;
    }
}
